package org.jeecg.modules.demo.crm.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.crm.dto.AuditParamDTO;
import org.jeecg.modules.demo.crm.dto.AuditParametersDTO;
import org.jeecg.modules.demo.crm.dto.CProjectApplicationDTO;
import org.jeecg.modules.demo.crm.dto.CSubProjectDTO;
import org.jeecg.modules.demo.crm.entity.CProjectHeadQuotes;
import org.jeecg.modules.demo.crm.entity.CProjectQuote;
import org.jeecg.modules.demo.crm.entity.CSubProject;
import org.jeecg.modules.demo.crm.mapper.CContractMapper;
import org.jeecg.modules.demo.crm.mapper.CProjectHeadQuotesMapper;
import org.jeecg.modules.demo.crm.mapper.CProjectQuoteMapper;
import org.jeecg.modules.demo.crm.service.ICCommonService;
import org.jeecg.modules.demo.crm.service.ICSubProjectService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 子项目信息表
 * @Author: jeecg-boot
 * @Date:   2025-05-27
 * @Version: V1.0
 */
@Api(tags="子项目信息表")
@RestController
@RequestMapping("/project/cSubProject")
@Slf4j
public class CSubProjectController extends JeecgController<CSubProject, ICSubProjectService> {
	@Autowired
	private ICSubProjectService cSubProjectService;

	@Autowired
	private ICCommonService commonService;

	 @Autowired
	 private CContractMapper cContractMapper;
	 @Autowired
	 private CProjectQuoteMapper cProjectQuoteMapper;

	
	/**
	 * 分页列表查询
	 *
	 * @param cSubProject
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "子项目信息表-分页列表查询")
	@ApiOperation(value="子项目信息表-分页列表查询", notes="子项目信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CSubProject>> queryPageList(CSubProject cSubProject,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        //QueryWrapper<CSubProject> queryWrapper = QueryGenerator.initQueryWrapper(cSubProject, req.getParameterMap());
		QueryWrapper<CSubProject> queryWrapper = new QueryWrapper<>();
		if(cSubProject != null  && StringUtils.isNotEmpty(cSubProject.getSubProjectName())){
			queryWrapper.like("sub_project_name",cSubProject.getSubProjectName());
		}
		if(cSubProject != null  && StringUtils.isNotEmpty(cSubProject.getProjectNumber())){
			queryWrapper.like("project_number",cSubProject.getProjectNumber());
		}
		if(cSubProject != null  && StringUtils.isNotEmpty(cSubProject.getProjectId())){
			queryWrapper.eq("project_id",cSubProject.getProjectId());
		}
		if(cSubProject != null  && StringUtils.isNotEmpty(cSubProject.getContactId())){
			queryWrapper.eq("contact_id",cSubProject.getContactId());
		}
		if(cSubProject != null && StringUtils.isNotEmpty(cSubProject.getStatus()) ){
			queryWrapper.eq("status",cSubProject.getStatus());
		}
		//queryWrapper.eq("del_flag",0);
		queryWrapper.orderByDesc("create_time");
		queryWrapper = commonService.permissionDetection(queryWrapper);
		Page<CSubProject> page = new Page<CSubProject>(pageNo, pageSize);
		IPage<CSubProject> pageList = cSubProjectService.page(page, queryWrapper);
		pageList.getRecords().stream().forEach(item -> {
			//合同金额
			BigDecimal contractPrice = cContractMapper.subProjectIdContract(item.getProjectId(),item.getId());
			item.setContractPrice(contractPrice);
			String contractFile = cContractMapper.getContractFile(item.getProjectId(),item.getId());
			item.setContractFile(contractFile);
			//报价 最新一条
			CProjectQuote quotes = cProjectQuoteMapper.findQuotes(item.getId());
			if(quotes != null){
				item.setTotalQuotation(quotes.getContractPrice());
			}else {
				item.setTotalQuotation(null);
			}
		});

		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param cSubProject
	 * @return
	 */
	@AutoLog(value = "子项目信息表-添加")
	@ApiOperation(value="子项目信息表-添加", notes="子项目信息表-添加")
	@RequiresPermissions("crm:application_subitems:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CSubProject cSubProject) {
		//LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		cSubProjectService.assignment(cSubProject);
		return Result.OK("指派成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cSubProject
	 * @return
	 */
	@AutoLog(value = "子项目信息表-编辑")
	@ApiOperation(value="子项目信息表-编辑", notes="子项目信息表-编辑")
	@RequiresPermissions("crm:application_subitems:add")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CSubProject cSubProject) {
		cSubProjectService.edit(cSubProject);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "子项目信息表-通过id删除")
	@ApiOperation(value="子项目信息表-通过id删除", notes="子项目信息表-通过id删除")
	@RequiresPermissions("crm:application_subitems:add")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cSubProjectService.deleteSubProject(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "子项目信息表-批量删除")
	@ApiOperation(value="子项目信息表-批量删除", notes="子项目信息表-批量删除")
	@RequiresPermissions("crm:application_subitems:add")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cSubProjectService.deleteBatch(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "子项目信息表-通过id查询")
	@ApiOperation(value="子项目信息表-通过id查询", notes="子项目信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CSubProject> queryById(@RequestParam(name="id",required=true) String id) {
		QueryWrapper<CSubProject> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id",id);
		queryWrapper = commonService.permissionDetection(queryWrapper);
		CSubProject cSubProject = cSubProjectService.getOne(queryWrapper);
		if(cSubProject==null) {
			return Result.error("未找到对应数据");
		}
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		cSubProject.setUserRole(sysUser.getRoleCode());
		return Result.OK(cSubProject);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cSubProject
    */
    @RequiresPermissions("project:c_sub_project:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CSubProject cSubProject) {
        return super.exportXls(request, cSubProject, CSubProject.class, "子项目信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("project:c_sub_project:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CSubProject.class);
    }


	 /**
	  *  子项目提交审核
	  *
	  * @param auditParametersDTO
	  * @return
	  */
	 @AutoLog(value = "子项目提交审核")
	 @ApiOperation(value="子项目提交审核", notes="子项目提交审核")

	 @RequestMapping(value = "/submitReview", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> submitReview(@RequestBody AuditParametersDTO auditParametersDTO) {
		 cSubProjectService.submitReview(auditParametersDTO);
		 return Result.OK("操作成功!");
	 }


	 /**
	  *  子项目审核
	  *
	  * @param auditParamDTO
	  * @return
	  */
	 @AutoLog(value = "子项目审核")
	 @ApiOperation(value="子项目审核", notes="子项目审核")
	 @RequestMapping(value = "/audit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> audit(@RequestBody AuditParamDTO auditParamDTO) {
		 cSubProjectService.audit(auditParamDTO);
		 return Result.OK("操作成功!");
	 }


	 @ApiOperation(value="子项目信息表list", notes="子项目信息表list")
	 @GetMapping(value = "/subprojectList")
	 public Result<List<CSubProject>> subprojectList(@RequestParam(name="projectId",required=true) String projectId) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 QueryWrapper<CSubProject> queryWrapper = new QueryWrapper<>();
		 if (!sysUser.getRoleCode().contains("admin") &&
				 !sysUser.getRoleCode().contains("财务") &&
		 !sysUser.getRoleCode().contains("项目经理") ){
			 queryWrapper.eq("assigned_to",sysUser.getId());
		 }
		 queryWrapper.eq("project_id",projectId);
		 queryWrapper.eq("del_flag",0);
		 queryWrapper.orderByDesc("create_time");
		 List<CSubProject> list = cSubProjectService.list(queryWrapper);
		 return Result.OK(list);
	 }


	 @AutoLog(value = "添加分包商")
	 @ApiOperation(value="添加分包商", notes="添加分包商")
	 @RequestMapping(value = "/saveContractorId", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> saveContractorId(@RequestBody CSubProject cSubProject) {
		 cSubProjectService.saveContractorId(cSubProject);
		 return Result.OK("操作成功!");
	 }

	 /**
	  * 子项目信息-详情
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="子项目信息-详情", notes="项目信息-详情")
	 @GetMapping(value = "/getOrderInfo")
	 public Result<CSubProjectDTO> getOrderInfo(@RequestParam(name="id",required=true) String id,
														@RequestParam(name="subProjectId",required=true) String subProjectId
	 ) {
		 //查询权限
		 QueryWrapper<CSubProject> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("id",subProjectId);
		 queryWrapper = commonService.permissionDetection(queryWrapper);
		 CSubProject cSubProject = cSubProjectService.getOne(queryWrapper);
		 if(cSubProject==null) {
			 return Result.error("未找到对应数据");
		 }
		 CSubProjectDTO data= cSubProjectService.getOrderInfo(id,subProjectId,cSubProject);
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 data.setSysUser(sysUser);
		 return Result.OK(data);
	 }


	 @AutoLog(value = "修改子项目状态")
	 @ApiOperation(value="修改子项目状态", notes="修改子项目状态")
	 @RequestMapping(value = "/updateStatus", method = {RequestMethod.PUT,RequestMethod.POST})
	 @RequiresPermissions("project:c_sub_project:quotationReview")
	 public Result<String> updateStatus(@RequestBody CSubProject cSubProject) {
		 cSubProjectService.updateStatus(cSubProject);
		 return Result.OK("操作成功!");
	 }


	 @ApiOperation(value="子项目信息表-状态", notes="子项目信息表-状态")
	 @GetMapping(value = "/statusCount")
	 public Result<Map<String,Long>> statusCount(CSubProject cSubProject,HttpServletRequest req) {
		 Map<String,Long> data = cSubProjectService.statusCount(cSubProject,req);
		 return Result.OK(data);
	 }



}
